package com.ir.stat.spark.config;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

@Component
@Provider
@AuthToken
@Priority(Priorities.USER)
public class AuthTokenFilter implements ContainerRequestFilter, ContainerResponseFilter {

    @Value("${auth.token}")
    private String authToken;

    @Value("${mode.debug}")
    private boolean debug;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        MultivaluedMap<String, String> headers = requestContext.getHeaders();
        if (!debug) {
            String token = headers.getFirst("X-AUTH-TOKEN");
            if (StringUtils.isBlank(token)) {
                Response response = Response.status(Response.Status.UNAUTHORIZED).entity("Authentication failed: token is null").build();
                requestContext.abortWith(response);
                return;
            }
            if (!token.equals(authToken)) {
                Response response = Response.status(Response.Status.UNAUTHORIZED).entity("Authentication failed: token is error").build();
                requestContext.abortWith(response);
                return;
            }
        }

    }

    @Override
    public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException {

    }
}
